﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.Blo;

namespace UI
{
    public class TreasureSelectPage : Page
    {
        public GameObject scrollView;
        public SimpleGrid simpleGrid;
        public GameObject itemPrefab;
        public UIToggle checkBox;
        public GameObject nextPageWordPref; //"点击显示下一页"

        public delegate void SelectCallback(List<string> guids);
        public SelectCallback m_callback;

        Dictionary<string,ChoseHeroItem> treasureItems = new Dictionary<string, ChoseHeroItem>();
        List<UITreasure> availableGuids = new List<UITreasure>();
        string treasureGuid;
        float waitTime = 0;
        int curShowedCount = 0;

        public void OnConfirmBtn()
        {
            List<string> selectGuids = new List<string>();
            foreach(var item in treasureItems)
            {
                bool value = item.Value.checkBox.GetComponent<UIToggle>().value;
                if (value)
                {
                    selectGuids.Add(item.Value.heroGuid);
                }
            }

            if (m_callback != null)
            {
                m_callback(selectGuids);
            }

            Close();
        }

        IEnumerator UpdatePanel()
        {
            treasureItems.Clear();

            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            yield return new WaitForSeconds(waitTime);
            
            if (curShowedCount == 0)
            {
                availableGuids = StaticData.playerData.InstPlayerData.GetUITreasureByType(0);
                StaticData.playerData.InstPlayerData.SortTreasureListForStrengthSelect(availableGuids);
            }

            int count = 0;
            for(int i = curShowedCount; i < availableGuids.Count; i++)
            {
                if(availableGuids[i].owner != null || availableGuids[i].refineLevel > 0 || availableGuids[i].guid == treasureGuid)
                {
                    continue;
                }
                GameObject obj = Instantiate(itemPrefab);
                simpleGrid.AddChild(obj);
                obj.GetComponent<ChoseHeroItem>().SetTreasure(availableGuids[i].guid);
                obj.GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIDragScrollView>().scrollView = scrollView.GetComponent<UIScrollView>();
                treasureItems[availableGuids[i].guid] = obj.GetComponent<ChoseHeroItem>();
                count++;

                if (count % 14 == 0)
                    yield return 1;
                if (count % 160 == 0 && i + 1 < availableGuids.Count)
                {
                    GameObject nextPageWordObj = Instantiate(nextPageWordPref);
                    nextPageWordObj.SetActive(true);
                    nextPageWordObj.GetComponent<NextPageWord>().m_callback = this.OnNextPage;
                    simpleGrid.AddChild(nextPageWordObj);
                    break;
                }
            }
            curShowedCount += count;
            scrollView.GetComponent<UIScrollView>().ResetPosition();

            Debug.Log(curShowedCount.ToString());
        }

        void OnNextPage()
        {
            waitTime = 0.01f;
            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());
        }

        public void OnOneKeySelect()
        {
            //清空之前的选择
            foreach (var item in treasureItems)
            {
                item.Value.checkBox.GetComponent<UIToggle>().value = false;
            }
            
            UITreasure treasure = StaticData.playerData.GetUITreasure(treasureGuid);
            
            long exp1 = DictTreasureStrengthBlo.GetTotalNeedExpToLevel(treasure.treasureData.quality, treasure.strengthLevel);
            long exp2 = DictTreasureStrengthBlo.GetTotalNeedExpToLevel(treasure.treasureData.quality, treasure.treasureData.maxStrengthen);
            long maxExpAllow = exp2 - exp1 - treasure.currentExp;
            long totalExp = 0;
            if (checkBox.value)
            {
                if (treasure.strengthLevel >= treasure.treasureData.maxStrengthen)
                {
                    checkBox.value = false;
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("treasure_level_max"));
                    return;
                }

                int count = 0;
                for (int i = 0; i < availableGuids.Count; i++)
                {
                    if (availableGuids[i].owner == null && 
                        (availableGuids[i].treasureData.quality < (int)QualityValue.PURPLE || availableGuids[i].treasureData.type == -1) 
                        && treasureItems.ContainsKey(availableGuids[i].guid) && availableGuids[i].guid != treasureGuid)
                    {
                        long tempexp = availableGuids[i].GetTreasureProvideExp();
                        if (totalExp >= maxExpAllow)
                        {
                            break;
                        }
                        else
                        {
                            count++;
                            treasureItems[availableGuids[i].guid].GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIToggle>().value = true;
                            totalExp += tempexp;
                            if (count >= 40)
                                break;
                        }
                    }
                }
                if (totalExp <= 0)
                {
                    //没有蓝色以下的卡可自动添加
                    checkBox.value = false;
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("no_treasure_under_purple"));
                    return;
                }
            }
        }

        protected override void DoOpen()
        {
            base.DoOpen();
            treasureGuid = options["guid"];

            GetComponent<PageTweener>().Play();

            waitTime = 0.5f;
            curShowedCount = 0;
            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());
        }

        protected override void DoClose()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            base.DoClose();
        }
    }
}
